package com.paulshiyc.imserver.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import com.paulshiyc.imserver.bean.User;
/**
 * im聊天通讯相关控制器
 * @author PaulShi
 *
 */
@Controller
public class ImController extends BaseController{
	/**
	 * 发送消息接口
	 * @param req 请求
	 * @param sendUsername 发送对象
	 * @param sendMsg	发送内容
	 * @return 响应结果
	 * @throws IOException io异常
	 */
	@RequestMapping("/sendMsg")
	@ResponseBody
	public String sendMsg(HttpServletRequest req,String sendUsername,String sendMsg) throws IOException {
		//根据发送对象用户名 获取webSocketSession对象
		WebSocketSession webSocketSession = onlinUser.get(sendUsername);
		//判断是否存在webSocketSession对象
		if(webSocketSession!=null) {
			//发送普通文本消息
			webSocketSession.sendMessage(new TextMessage(sendMsg));
		}
		logger.info(sendMsg);
		//响应结果
		return "success";
	}
	/**
	 * 获取所有在线用户
	 * @param req 请求
	 * @return 响应结果
	 */
	@RequestMapping("/getOnlinUsers")
	@ResponseBody
	public List<User> getOnlinUsers(HttpServletRequest req){
		//创建结果容器 长度等于im在线用户长度
		List<User> list = new ArrayList<User>(onlinUser.size());
		//遍历im在线key 即获取所有在线用户名
		for (String username : BaseController.onlinUser.keySet()) {
			//根据用户名获取sessionId
			String userSessionId = userNameAndSession.get(username);
			//根据sessionId获取用户信息并添加到结果容器
			list.add(sessionAndUser.get(userSessionId));
		}
		//响应结果
		return list;
	}
}
